package com.sne.monitor.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.sne.common.constant.RedisConstant;
import com.sne.common.entity.RedisUserInfo;
import com.sne.monitor.service.IMonitorUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户在线监控服务实现类
 * @author fanghh
 * @date 2020/11/23
 */
@Service
public class MonitorUserServiceImpl implements IMonitorUserService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public List<RedisUserInfo> list() {
        Set<String> keys = redisTemplate.keys(RedisConstant.TOKEN + "*");
        if(CollectionUtils.isEmpty(keys)){
            return null;
        }
        return keys.stream().map(key -> {
            String data = redisTemplate.opsForValue().get(key);
            RedisUserInfo userInfo = JSONObject.parseObject(data, RedisUserInfo.class);
            if (userInfo != null) {
                userInfo.setToken(key.replace(RedisConstant.TOKEN, ""));
            }
            return userInfo;
        }).collect(Collectors.toList());
    }

    @Override
    public boolean deleteByToken(String token) {
        redisTemplate.delete(RedisConstant.TOKEN+token);
        return true;
    }

    @Override
    public boolean deleteByTokens(List<String> tokens) {
        List<String> keys = tokens.stream().map(token -> RedisConstant.TOKEN + token).collect(Collectors.toList());
        redisTemplate.delete(keys);
        return true;
    }

}
